package fatworm.metadata;

import java.util.*;

import fatworm.storage.table.*;
import fatworm.tx.*;

public class StatMgr
{
    private HashMap<String, StatInfo> tablestats;
    private int numCalls;
    private TableMgr tblmgr;

    public StatMgr(TableMgr tblmgr, Transaction tx)
    {
        this.tblmgr = tblmgr;
        refreshStatistics(tx);
    }
    public synchronized StatInfo getStatInfo(String tblname, TableInfo ti, Transaction tx)
    {
        numCalls++;
        if (numCalls > 100)
            refreshStatistics(tx);
        StatInfo si = tablestats.get(tblname);
        if (si == null)
        {
            refreshTableStats(tblname, tx);
            si = tablestats.get(tblname);
        }
        return si;
    }
    private synchronized void refreshStatistics(Transaction tx)
    {
        tablestats = new HashMap<String, StatInfo>();
        numCalls = 0;
        TableInfo tcatInfo = tblmgr.getTableInfo("tblcat", tx);
        HeapFile tcatfile = new HeapFile(tcatInfo, tx);
        while (tcatfile.next())
        {
            String tblname = tcatfile.getValue("tblname").toString();
            refreshTableStats(tblname, tx);
        }
        tcatfile.close();
    }
    private synchronized void refreshTableStats(String tblname, Transaction tx)
    {
        int numRecs = 0;
        TableInfo ti = tblmgr.getTableInfo(tblname, tx);
        HeapFile rf = new HeapFile(ti, tx);
        while (rf.next())
            numRecs++;
        int blknum = rf.currentRid().blknum;
        int numblocks = 1 + blknum;
        StatInfo si = new StatInfo(numblocks, numRecs);
        tablestats.put(tblname, si);
        rf.close();
    }
}